package com.googlecode.cswish.struts;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.dispatcher.mapper.ActionMapping;

/**
 * Add additional mapping: '/' --> index.html
 * 
 * @author Jerry
 */
public class StrutsPrepareAndExecuteFilter extends org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter {
	
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        try {
            prepare.setEncodingAndLocale(request, response);
            prepare.createActionContext(request, response);
            prepare.assignDispatcherToThread();
			if ( excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {
				chain.doFilter(request, response);
			} else {
				request = prepare.wrapRequest(request);
				ActionMapping mapping = prepare.findActionMapping(request, response, true);
				if (mapping == null) {
					String uri = Routing.getUri(request);
					if (uri.length() == 0 || uri.charAt(uri.length() - 1) == '/') {
						String location = uri + "index.html";
						response.sendRedirect(location);
						return ;
						
//						mapping = new ActionMapping();
//				        mapping.setExtension("html");
//				        mapping.setName(uri + "index");
//				        mapping.setNamespace("");
//						request.setAttribute("struts.actionMapping", mapping);
					}
				}
				
				if (mapping == null) {
					boolean handled = execute.executeStaticResourceRequest(request, response);
					if (!handled) {
						chain.doFilter(request, response);
					}
				} else {
					execute.executeAction(request, response, mapping);
				}
			}
        } finally {
            prepare.cleanupRequest(request);
        }
    }
}
